﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using TextReplace.Models;

namespace TextReplace.Methods
{
    public class ReplaceHelper
    {
        const string searchExtendName = "searchExtendName";
        DisplayModel displaymodel = new DisplayModel();
        int lineRowNum = 0;
        bool IsMatch = false;
        public DisplayModel SearchFolderAndReplace(string folderPath)
        {
            var extends = ConfigHelper.GetAppSettings(searchExtendName).Split(',');
            DirectoryInfo theFolder = new DirectoryInfo(folderPath);
            try
            {
                foreach (var file in theFolder.GetFiles())
                {
                    var path = file.FullName.Replace(@"\", ".");
                    var pathmMatche = Regex.Match(path, @".(Scripts.Code.\S+?).view.");
                    if (pathmMatche.Groups.Count > 1&& extends.Contains(file.Extension))
                    {
                        var storePath = $"{pathmMatche.Groups[1]}.store.";
                        ReadFileAndReplace(file.FullName, storePath);
                    }
                   
                }
                foreach (var folder in theFolder.GetDirectories())
                {
                    SearchFolderAndReplace(folder.FullName);
                }
            }
            catch(UnauthorizedAccessException unAccessEx)
            {
                displaymodel.ExceptionContent.AppendLine(unAccessEx.Message);
            }
            return displaymodel;
        }
        private void Init()
        {
            IsMatch = false;
            lineRowNum = 0;
        }
        private void AddFileName(string fileNameWithPath)
        {
            displaymodel.BeforeContent.AppendLine(fileNameWithPath);
            displaymodel.OverContent.AppendLine(fileNameWithPath);
        }
        private void RemoveFileNameIfNotNeed(string fileNameWithPath)
        {
            if (!IsMatch)
            {
                var pathlength = fileNameWithPath.Length + 2;
                displaymodel.BeforeContent.Remove(displaymodel.BeforeContent.Length - pathlength, pathlength);
                displaymodel.OverContent.Remove(displaymodel.OverContent.Length - pathlength, pathlength);
            }
        }
        protected void ReadFileAndReplace(string fileNameWithPath,string storePath)
        {
            var replaceModel = new ReplaceModel();
            var fileEncoding = EncodingHelper.GetEncoding(fileNameWithPath, Encoding.Default);
            using (StreamReader sr = new StreamReader(fileNameWithPath, fileEncoding))
            {
                Init();
                AddFileName(fileNameWithPath);
                string lineData;
                replaceModel.FileName = fileNameWithPath;
                replaceModel.FileEncoding=fileEncoding;
                while ((lineData = sr.ReadLine()) != null)
                {
                    lineRowNum++;
                    lineData = MatchLineAndReplace(lineData, storePath);
                    replaceModel.FileContent.AppendLine(lineData);
                }
                RemoveFileNameIfNotNeed(fileNameWithPath);
            }
            if (IsMatch)
            {
                displaymodel.ReplaceModels.Add(replaceModel);
            }
          
        }

        public string MatchLineAndReplace(string linedata,string storePath)
        {
            var matchpattern = @"store\s*?\:\s*?(\'|"")\s*?(\S+?Store)\s*?(\'|"")";
          
            if (Regex.IsMatch(linedata,matchpattern))
            {
                IsMatch = true;
                displaymodel.BeforeContent.AppendLine($"行数:{lineRowNum}  内容：{linedata}");
                displaymodel.SearchRowCount++;
                var matches = Regex.Matches(linedata, matchpattern);
                foreach (Match match in matches)
                {
                    var storeName = match.Groups[2];
                    var replacePattern = $@"store\s*?\:\s*?(\'|"")\s*?({storeName})\s*?(\'|"")";
                    linedata = Regex.Replace(linedata, replacePattern, $"store:Ext.create('{storePath}{storeName}');");
                }
                   
                displaymodel.OverContent.AppendLine($"行数:{lineRowNum}  内容：{linedata}");
            }
           
            return linedata;
        }

    }
}
